package com.wunong.smart.bigdata.jdk;

import java.util.concurrent.RecursiveTask;

/**
 * <a href="https://www.infoq.cn/article/fork-join-introduction">fork join框架</a>
 * 1. 解决的是任务并行问题，原理为分治
 * 2. 分解子任务，而后则合并子任务结果再执行
 */
public class SumJoinTask extends RecursiveTask<Integer> {

    private final int start;
    private final int end;

    /**
     * 分片大小
     */
    private final int threshold = 2;

    public SumJoinTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        // 判断是否任务分配完成
        boolean canCompute = end - start <= threshold;

        if (canCompute) {
            return this.sum();
        }

        int mid = (start + end) / 2;
        SumJoinTask leftTask = new SumJoinTask(start, mid);
        SumJoinTask rightTask = new SumJoinTask(mid + 1, end);

        // 利用fork方法：执行子任务
        leftTask.fork();
        rightTask.fork();

        // 利用join方法：合并子任务结果
        return leftTask.join() + rightTask.join();
    }

    /**
     * 求和
     *
     * @return
     */
    public Integer sum() {
        // 求和
        int sum = 0;
        for (int i = start; i <= end; i++) {
            sum += i;
        }
        return sum;
    }

}